<?php
include_once 'core.php';
include_once 'fun.php';

define('游客', 0);
define('巡查员', 1);
define('库管员', 2);
define('信息员', 3);
define('管理员', 4);

define('c', [
  'get' => 0,
  'up' => 1,
  'add' => 2,
  'del' => 3,
  'reg' => 1001, // 注册
  'getToken' => 1002, // 获取token
  'getTokenByWxID' => 1003, // 使用token
  'getMenu' => 1004,
  'getGlobal4' => 1005, // 获取cars,itemType,notice,promise

  'getIndex' => 2001, // 获取主页数据

  'openssl_get_cipher_methods' => 999999,
  'end' => -1
]);
define('noPrem', [
  'msg' => '没有权限'
]);

function getPid($table, $id, $retPid = false) {
  $ret = [];
  $r = GetData(['table' => $table, 'id' => $id], 'id,pid', true);
  if ($r['error']) $ret = [];
  else {
    if ($retPid) return $r['pid'];
    if ($r['pid']) {
      $ret = getPid($table, $r['pid']);
      $ret[] = $id;
    } else $ret = [$id];
  }
  return $ret;
}
function addStock($depository, $project, $item, $sum) {
  // 确认仓库
  $t = GetData(['table' => 'depository', 'id' => $depository], 'id', true);
  if ($t['error']) return ['error' => '没有找到仓库' . $depository];
  $p = getPid('project', $project);
  $s = count($p);
  if ($s < 1) return ['error' => '没有找到项目' . $project];
  $tmp = [
    'table' => 'stock',
    'project' => $project,
    'item' => $item
  ];
  $t = GetData($tmp, 'id,depository');
  if ($t['error']) return ['error' => "项目$project 下没有物料$item"];
  $tmp = arrKeyIn($t, $depository, 'depository');
  if (!$tmp) {
    $tmp = arrKeyIn($t, 0, 'depository');
    if ($tmp) UpData(['table' => 'stock', 'depository' => $depository, 'where' => ['id' => $tmp['id']]]);
    else {
      $tmp = AddData([
        'table' => 'stock',
        'depository' => $depository,
        'project' => $project,
        'item' => $item,
        'sum' => 0,
        'arrived' => 0,
        'use' => 0,
        'stock' => 0,
        'state' => 0
      ]);
    }
  }
  // 仓库 项目 物料均存在.开始更新列
  $tmp = [
    'table' => 'stock',
    'arrived' => "=arrived+$sum",
    'stock' => "=stock+$sum",
    'where' => ['id' => $tmp['id']]
  ];
  $tmp = UpData($tmp, false, true);
  return $tmp;
}
function getStock($depository, $project, $item, $process, $retID = false) {
  $t = GetData([
    'table' => 'stock',
    'depository' => $depository,
    'project' => $project,
    'item' => $item,
    'process' => $process
  ], '*', true);
  if ($t['error']) { // 新建信息
    $t = AddData([
      'table' => 'stock',
      'depository' => $depository,
      'project' => $project,
      'item' => $item,
      'process' => $process,
      'sum' => is_numeric($retID) ? $retID : 0,
      'arrived' => 0,
      '`use`' => 0,
      'stock' => 0,
      'state' => 0
    ]);
    if ($t['error']) return $t;
  }
  if ($retID === true) {
    if ($t['id']) $t = $t['id'];
    elseif (sureArray($t)) $t = $t[0];
  }
  return $t;
};
function checkItemIO_f($items, $token) {
  $ret = [];
  // 拥有权限的 仓库列表
  $d = GetData(['table' => 'depository', 'userType' => $token['uts']], 'id', true);
  // 拥有权限的 项目列表
  $p = GetData(['table' => 'project', 'userType' => $token['uts']], 'id', true);
  foreach ($items as $key => $value) {
    $value['depository'] = (int) $value['depository'];
    $value['project'] = (int) $value['project'];
    $value['item'] = (int) $value['id'];
    $value['sum'] = (int) $value['sum'];
    if (!(in_array($value['depository'], $d) && in_array($value['project'], $d))) return ['error' => '没有操作当前库或者项目的权限', 'data' => $value];
    $pid = getPid('project', $value['project']);
    if (!$pid) return ['error' => '获取上级项目错误.'];
    foreach ($pid as $v) {
      $t = getStock($value['depository'], $v, $value['item'], true);
      if ($t['error']) return $t;
      if (!$t) return ['error' => '系统错误101'];
      $ret[] = [
        'table' => 'stock',
        'arrived' => '=arrived+' . $value['sum'],
        'stock' => '=stock+' . $value['sum'],
        'where' => ['id' => $t]
      ];
    }
  }
  return $ret;
};
function checkItemIO($items, $token) {
  $ret = [];
  // 拥有权限的 仓库列表
  $d = GetData(['table' => 'depository', 'userType' => $token['uts']], 'id', true);
  // 拥有权限的 项目列表
  $p = GetData(['table' => 'project', 'userType' => $token['uts']], 'id', true);
  foreach ($items as $key => $value) {
    mPrintX($value);
    // $value['depository'] = (int) $value['depository'];
    // $value['project'] = (int) $value['project'];
    // $value['item'] = (int) $value['id'];
    // $value['sum'] = (int) $value['sum'];
    // if (!(in_array($value['depository'], $d) && in_array($value['project'], $d))) return ['error' => '没有操作当前库或者项目的权限', 'data' => $value];
    // $t = getStock($value['depository'], $value['project'], $value['item'], true);
    // if ($t['error']) return $t;
    // if (!$t) return ['error' => '系统错误101'];
    // $t = [
    //   'table' => 'stock',
    //   'arrived' => '=arrived+' . $value['sum'],
    //   'stock' => '=stock+' . $value['sum'],
    //   'where' => ['id' => $t]
    // ];
    // if ($value['sum'] < 0) $t['`use`'] = '=`use`+' . abs($value['sum']);
    // $ret[] = GetData(['table' => 'stock', 'id' => $t['id']], '*', true);
  }
  return $ret;
};

function getUserType($token, $retID = false) {
  $ret = GetData(['table' => 'userType']);
  if ($ret['error']) return [0];
  if ($token['type'] == 管理员) {
    if ($retID) {
      $t = [0];
      foreach ($ret as $v) {
        $t[] = $v['id'];
      }
      $ret = $t;
    }
  } else $ret = pushPid($ret, $token['userType'], $retID ? 'id' : false);
  return $ret;
}
function getStockAll($ut) {
  $ret = GetData([
    'table' => 'project',
    'userType' => $ut
  ], 'id', true);
  $ret = GetData([
    'table' => 'stock',
    'project' => $ret
  ]);
  return $ret;
};

$fun = [];

$fun[c['get']] = function ($cmd, $token = false) {
  $ret = $token ? $token : useToken($cmd);
  if ($ret) {
    $ret['uts'] = getUserType($ret, true);
    include_once "get.php";
    if (isset($get[$cmd['table']])) return $get[$cmd['table']]($cmd, $ret);
    else return ['msg' => 'val参数错误,table不符合规范', 'data' => $cmd];
  } else return noPrem;
};

$fun[c['up']] = function ($cmd, $token = false) {
  $ret = $token ? $token : useToken($cmd);
  if ($ret && in_array($ret['type'], [管理员, 信息员, 库管员])) {
    $ret['uts'] = getUserType($ret, true);
    include_once 'up.php';
    if (isset($up[$cmd['table']])) return $up[$cmd['table']]($cmd, $ret);
    else return ['msg' => 'val参数错误,table不符合规范', 'data' => $cmd];
  } else return noPrem;
};

$fun[c['add']] = function ($cmd, $token = false) {
  $ret = $token ? $token : useToken($cmd);
  if ($ret && in_array($ret['type'], [管理员, 信息员, 库管员])) {
    $ret['uts'] = getUserType($ret, true);
    include_once "add.php";
    if (isset($add[$cmd['table']])) return $add[$cmd['table']]($cmd, $ret);
    else return ['msg' => 'val参数错误,table不符合规范', 'data' => $cmd];
  } else return noPrem;
};



$fun[c['getToken']] = function ($cmd) {
  $ret = getToken($cmd);
  if ($ret) $ret = ['result' => $ret];
  else $ret = ['msg' => '用户名或密码错误', 'data' => $cmd];
  return $ret;
};
$fun[c['getTokenByWxID']] = function ($cmd) {
  $ret = GetData(['table' => 'users', 'openID' => $cmd['openID']], 'id,username,password,type', true);
  if ($ret) {
    $ret['uniqid'] = uniqid();
    $ret = ['token' => enAes($ret)];
    $ret = ['result' => $ret];
  } else $ret = ['msg' => 'val参数错误,val必须设置属性openID(大小写敏感)', 'data' => $cmd];
  return $ret;
};

function getGlobal4($cmd, $token = false) {
  // return [];
  $time = [];
  $rt = microtime(true);
  $token = $token ? $token : useToken($cmd);
  // return $token;
  $ret = [];
  if ($token) {
    $ret['items'] = GetData(['table' => 'items']);
    if ($ret['items']['error']) $ret['items'] = [];

    $ret['itemType'] = GetData(['table' => 'itemType']);
    if ($ret['itemType']['error']) $ret['itemType'] = [];

    $ret['userType'] = getUserType($token); // 获取所属部门及下级部门的id
    if ($ret['userType']['error']) $ret['userType'] = [];
    $prem = getUserType($token, true);
    // if ($ret['userType']) { // 将上级目录加入进去.权限不变
    //   while ($ret['userType'][0]['pid']) {
    //     $t = GetData([
    //       'table' => strtolower('userType'),
    //       'id' => $ret['userType'][0]['pid']
    //     ], '*', true);
    //     array_unshift($ret['userType'],$t);
    //   }
    // }

    $ret['users'] = GetData(['table' => 'users', 'userType' => $prem]);
    if ($ret['users']['error']) $ret['users'] = [];
    if ($token['type'] != 管理员) {
      foreach ($ret['users'] as $k => $value) {
        if ($value['id'] != $token['id']) {
          $ret['users'][$k]['username'] = '';
          $ret['users'][$k]['password'] = '';
        }
      }
    }

    $ret['depository'] = GetData(['table' => 'depository', 'userType' => $prem]);
    if ($ret['depository']['error']) $ret['depository'] = [];

    $ret['userType2'] = [
      ['id' => 1, 'name' => '巡查员'],
      ['id' => 2, 'name' => '库管'],
      ['id' => 3, 'name' => '信息'],
      ['id' => 4, 'name' => '超级管理员'],
    ];
    $ret['process'] = GetData(['table' => 'process']);
    if ($ret['process']['error']) $ret['process'] = [];

    $ret['project'] =  GetData(['table' => 'project', 'userType' => $prem]);
    if ($ret['project']['error']) $ret['project'] = [];

    $ret['stock'] = getStockAll($prem);
    if ($ret['stock']['error']) $ret['stock'] = [];

    $ret['me'] = $token;
    // unset($ret['me']);
  }
  // $ret=[];
  // $ret['items'] = [];
  // $ret['stock'] = [];
  // $ret=['stock'=> $ret['stock']];
  $time['逻辑处理耗时'] = microtime(true) - $rt;
  $ret['logicTime'] = $time;
  return $ret;
};
$fun[c['getGlobal4']] = function ($cmd) {
  return getGlobal4($cmd);
};

function getProcessByName($name) {
  $t = GetData(['table' => 'process', 'name' => $name]);
  if ($t['error']) $t = AddData(['table' => 'process', 'name' => $name, 'other' => '{"remarks":"批量添加"}', 'state' => 1]);
  else $t = $t[0];
  return $t['id'];
}
function getProjectByName($name, $pid = 0, $userType = 0) {
  if (!$pid) $pid = 0;
  $d = ['table' => 'project', 'name' => $name, 'pid' => $pid ? $pid : 0, 'userType' => $userType ? (int) $userType : 1];
  $t = GetData($d);
  if ($t['error']) {
    $d['process'] = '[]';
    $d['other'] = '{"remarks":"批量添加"}';
    $d['state'] = 1;
    $t = AddData($d);
  } else $t = $t[0];
  return (int) $t['id'];
}
function getItemByName($uid, $name, $model, $units = '[]', $sum = 0, $state = 1, $other = '{"remarks":"批量添加"}', $cid = 0, $pid = 0) {
  $s = ['table' => 'items', 'uid' => $uid, 'name' => $name, 'model' => $model];
  $t = GetData($s);
  if ($t['error']) {
    $s = ['table' => 'items', 'uid' => $uid, 'name' => $name, 'model' => $model, 'units' => $units, 'sum' => $sum, 'state' => $state, 'other' => $other, 'cid' => $cid, 'pid' => $pid];
    $t = AddData($s);
  } else $t = $t[0];
  return (int) $t['id'];
}
function getDepositoryByName($name, $pid = 0, $userType = 1, $other = '{"remarks":"批量添加"}') {
  $s = ['table' => 'depository', 'name' => $name];
  $t = GetData($s);
  if ($t['error']) {
    $s = ['table' => 'depository', 'name' => $name, 'pid' => $pid, 'userType' => $userType, 'other' => $other];
    $t = AddData($s);
  } else $t = $t[0];
  return (int) $t['id'];
}
